package com.lt.crm.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lt.crm.pojo.BasDict;
import com.lt.crm.service.BasDictService;
import javax.annotation.Resource;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/dict")
public class DictController {

    @Resource
    BasDictService basDictService;

    @RequestMapping("/list")
    public String list(@RequestParam(required = false, defaultValue = "") Integer dictId,
                       @RequestParam(required = false, defaultValue = "") String dictItem,
                       @RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                       Model model) {
        Page<BasDict> page = new Page<>(pageIndex, 5);
        Page<BasDict> page2 = basDictService.findByDictIdAndAndDictValue(dictId,dictItem,page);
        model.addAttribute("dictPage", page2);
        model.addAttribute("dictId", dictId);
        model.addAttribute("dictValue", dictItem);
        return "dict/list";
    }

    @RequestMapping("/save")
    public String save(BasDict dict) {
        try {
            basDictService.saveOrUpdate(dict);
            return "redirect:/dict/list";
        } catch (Exception e) {
            return "dict/add";
        }
    }

    @RequestMapping("/edit")
    public String edit(@RequestParam Integer dictId, Model model) {
        model.addAttribute("dict", basDictService.getById(dictId));
        return "dict/edit";
    }

    @RequestMapping("/add")
    public String add() {
        return "dict/add";
    }

    @RequestMapping("/del/{dictId}")
    @ResponseBody
    public Map del(@PathVariable Integer dictId) {
        Map map = new HashMap<>();
        try {
            basDictService.removeById(dictId);
            map.put("delResult", "true");
        } catch (Exception e) {
            map.put("delResult", "false");
        }
        return map;
    }
}
